package gamagora.game.animations
{
	import gamagora.game.map.OSWorldMap;
	import gamagora.game.utils.OSImages;
	
	import org.flixel.FlxG;
	import org.flixel.FlxSprite;
	
	public class OSBird extends OSAnimation
	{
		private static const IDLE:String = "idle";
		private static const START_FLY:String = "sf";
		private static const FLY:String = "fly";
		
		private static const SPEED_X:Number = 100.0;
		private static const SPEED_Y:Number = 100.0;
		private static const PLAYER_MAX_DIST:Number = 100.0;
		private static const Y_DIST_BEFORE_KILL:Number = -40.0;
		
		private var _dirX:Number;
		private var _flyingAtStart:Boolean;
		private var _timeBeforeUp:Number;
		private var _counter:Number;
		
		public function OSBird(X:Number=0, Y:Number=0, background:uint = OSAnimation.NO_BACKGROUND, flyingAtStart:Boolean = false, timeBeforeUp:Number = 5)
		{
			super(X, Y, background);
			_flyingAtStart = flyingAtStart;
			_timeBeforeUp = timeBeforeUp;
			_counter = 0;
			
			if(background != OSAnimation.NO_BACKGROUND)
			{
				loadGraphic(OSImages.BIRD2, true, true, 36, 36);
				offset.x = 18;
				offset.y = 26;
			}
			else 
			{
				loadGraphic(OSImages.BIRD, true, true, 72, 72);
				offset.x = 36;
				offset.y = 52;
			}
			
			addAnimation(IDLE, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0], 4);
			addAnimation(START_FLY, [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25], 8, false);
			addAnimation(FLY, [26, 27, 28, 29, 30, 31, 32, 33, 34], 8);
			
			if(!_flyingAtStart)
			{
				var angle:Number = (Math.random() * 60);
				_dirX = Math.cos(Math.PI * angle / 180);
				_dirX *= (uint(Math.random() * 2) == 0) ? -1 : 1;
				_facing = _dirX > 0 ? LEFT : RIGHT;
				play(IDLE);
			}
			else 
			{
				_dirX = _facing == LEFT ? 1 : -1;
				play(FLY);
			}
		}
		
		public override function update():void
		{
			if(_flyingAtStart)
			{
				x += FlxG.elapsed * _dirX * SPEED_X;
				
				if(_counter >= _timeBeforeUp)
				{
					y -= FlxG.elapsed * SPEED_Y;
				}
				else 
				{
					_counter += FlxG.elapsed;
				}
			}
			else 
			{
				switch(_curAnim.name)
				{
					case IDLE:
						if(x - OSWorldMap.player.x < PLAYER_MAX_DIST)
						{
							play(START_FLY);
						}
						break;
					case START_FLY:
						if(finished)
						{
							play(FLY);
						}
						break;
					case FLY:
						x += FlxG.elapsed * _dirX * SPEED_X;
						y -= FlxG.elapsed * SPEED_Y;
						break;
				}
			}
			
			if(y < Y_DIST_BEFORE_KILL)
			{
				kill();
			}
			
			super.update();
		}
	}
}
